<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-04-21 14:16:03
 * @LastEditTime: 2022-04-21 15:23:18
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 责任链模式
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>责任链模式</title>
</head>

<body>
  <!-- 模拟充值后领取优惠券 -->
</body>
<script>
  /* 
  1.充值(isPay = true) 500元(orderType = 1) 获得 100元 优惠券
  2.充值 200元 获得 20元 优惠券
  3.不充值(isPay = false)根据优惠券库存(count)获得 10元 优惠券
  */

  /*   function order(orderType, isPay, count) {
      if (orderType === 1) {
        if (isPay) {
          console.log('获得100元优惠券');
        } else {
          if (count > 0) {
            console.log('获得10元优惠券');
          } else {
            console.log('什么也咩有');
          }
        }
      } else if (orderType === 2) {
        if (isPay) {
          console.log('获得20元优惠券');
        } else {
          if (count > 0) {
            console.log('获得10元优惠券');
          } else {
            console.log('什么也咩有');
          }
        }
  
      } else if (orderType === 3) {
        if (count > 0) {
          console.log('获得10元优惠券');
        } else {
          console.log('什么也咩有');
        }
      }
    } */

  function chainOrder500(orderType, isPay, count) {
    if (orderType === 1 && isPay) {
      return console.log('获得100元优惠券');
    }
    return 'nextSuccessor'
  }

  function chainOrder200(orderType, isPay, count) {
    if (orderType === 1 && isPay) {
      return console.log('获得100元优惠券');
    }
    return 'nextSuccessor'
  }

  function chainOrderNormal(orderType, isPay, count) {
    if (count > 0) {
      return console.log('获得10元优惠券');
    }
    return console.log('什么也咩有');
  }

  class Chain {
    constructor(fn) {
      this.fn = fn
      this.success = null
    }
    setNextSuccessor(success) {
      return this.success = success
    }
    passRequest() {
      const res = this.fn.apply(this, arguments)
      if (res === 'nextSuccessor') {
        return (
          this.success && this.success.passRequest.apply(this.success, arguments)
        )
      }
      return res
    }
  }
  const c1 = new Chain(chainOrder500)
  const c2 = new Chain(chainOrder200)
  const c3 = new Chain(chainOrderNormal)

  c1.setNextSuccessor(c2)
  c2.setNextSuccessor(c3)

  c1.passRequest(1,false,500)

</script>

</html>